<template lang="pug">
  .ApplyInvoice
    Modal(
      v-model="isShowBalanceProcessModal"
      title="差额处理"
      class-name="vertical-center-modal"
      width="800"
      :mask-closable="false"
    )
      .search-form
        Form.ivu-row(ref="formData" :model="formData" :rules="rules" :label-width="120")
          FormItem.form-item.ivu-col(v-for="(item, index) of formItem" :label="item.label" :key="index" :class="item.style" :prop="item.prop" v-if="item.isShow")
            template(v-if="item.type === 'text'")
              .line-h-30 {{formData[item.model]}}
            template(v-if="item.type === 'select'")
              //- Select(v-model="formData[item.model]" :placeholder="item.placeholder")
              //-   Option(v-for="(c_item, c_index) of arrListDown[item.options]" :key="c_index" :value="c_item.value") {{c_item.label}}
              //- 差额所属项目
              Select(v-if="item.model === 'insuranceCode'" v-model="formData[item.model]" :placeholder="item.placeholder" clearable label-in-value @on-change="balanceInsuranceNameChange")
                Option(
                  v-for="(c_item, index) in arrListDown[item.options]"
                  :value="c_item.code"
                  :key="index"
                ) {{ c_item.name }}
              //- 差额所属编号
              Select(v-if="item.model === 'insureNo'" v-model="formData.insureNo" :placeholder="item.placeholder" clearable)
                Option(
                  v-for="(c_item, index) in arrListDown[item.options]"
                  :value="c_item"
                  :key="index"
                ) {{ c_item }}
              //- 差额所属编号-非必填
              Select(v-if="item.model === 'insureNoOther'" v-model="formData.insureNo" :placeholder="item.placeholder" clearable)
                Option(
                  v-for="(c_item, index) in arrListDown[item.options]"
                  :value="c_item"
                  :key="index"
                ) {{ c_item }}
            template(v-if="item.type === 'input'")
              Input(v-model="formData[item.model]" :placeholder="item.placeholder")
            template(v-if="item.type === 'textarea'")
              Input(v-model="formData[item.model]" :placeholder="item.placeholder" type="textarea" :rows="3")
            template(v-if="item.type === 'button'")
              Button.ml-20.pull-right(type="info" @click="handleAddBalance") 添加

      Table.hasTitle-table.beautiful-table(:columns="thead" :data="tableData" :stripe="true" ref="demoTable" max-height="280")
        .clearfix.pr-24.pl-12.overflow-hidden(slot="header")
          .table-title-lefttxt.pull-left
            |当期差额总计
            span.text-info.pl-5.pr-5.font-weight {{currentRow.currentBalanceTotal}}
            |元
        template(slot-scope="{ row, index }" slot="action")
          Button.mr-10(type="text" size="small" @click="handleDel(index)" :disabled="row.id ? true : false") 删除

      .clearfix(slot="footer")
        Button(type="text" @click="cancel") 取消
        Button(type="primary" @click="handleSubmit") 确定
</template>

<script>
// import { InvoiceApi } from '@/api/Invoice.api.js'
import { ReceivableBillApi } from '@/api/ReceivableBill.api.js'
import { Common } from '@/utils/common.js'
import _cloneDeep from 'clone-deep'
import { BalanceProcessModalThead } from '../ARtableHead.js'
export default {
  name: '',

  watch: {
  },

  computed: {

  },

  data () {
    const validateTotal = (rule, value, callback) => {
      if (!this.formData.total || this.formData.total == 0) {
        callback(new Error('请输入非0的数字'))
      } else {
        callback()
      }
    }
    
    return {
      isShowBalanceProcessModal: false,
      thead: _cloneDeep(BalanceProcessModalThead),
      tableData: [],
      tableComone: {
        pageIndex: 1, // 页码
        totalRows: 0, // 总条数
        pageSize: 10, // 当前页面展示条数
        inServiceCount: 0, // 在职
        outServiceCount: 0 // 离职
      },
      formData: {
        id: '',
        insuranceName: '',
        insuranceCode: '',
        insureNo: '',
        insureNoOther: '',
        total: '',
        remark: ''
      },
      formItem: [
        { type: 'select', label: '差额所属项目：', placeholder: '请选择差额所属项目', prop: 'insuranceCode', model: 'insuranceCode', style: 'ivu-col-span-12', options: 'balanceProgramNames', isShow: true },
        { type: 'select', label: '差额所属编号：', placeholder: '请选择差额所属编号', prop: 'insureNo', model: 'insureNo', style: 'ivu-col-span-12', options: 'balanceNos', isShow: true },
        { type: 'select', label: '差额所属编号：', placeholder: '请选择差额所属编号', prop: 'insureNoOther', model: 'insureNoOther', style: 'ivu-col-span-12', options: 'balanceNos', isShow: false },
        { type: 'input', label: '当期差额：', placeholder: '请输入当期差额', prop: 'total', model: 'total', style: 'ivu-col-span-12', isShow: true },
        { type: 'textarea', label: '差额说明：', placeholder: '请输入差额说明', prop: 'remark', model: 'remark', style: 'ivu-col-span-24', isShow: true },
        { type: 'button', style: 'ivu-col-span-24', isShow: true }
      ],
      rules: {
        insuranceCode: [
          { required: true, message: '请选择差额所属项目', trigger: 'select' }
        ],
        insureNo: [
          { required: true, message: '请选择差额所属编号', trigger: 'select' }
        ],
        total: [
          // { required: true, message: '请输入当期差额(不能为0)', trigger: 'blur', pattern: /^-?[1-9]\d*$/ }
          { required: true, message: '请输入当期差额(不能为0)', trigger: 'blur', validator: validateTotal }
        ],
        remark: [
          { required: true, message: '请输入差额说明', trigger: 'blur' }
        ]
      },
      arrListDown: {
        balanceProgramNames: [],
        balanceNos: []
      },
      rowYear: '',
      rowMonth: '',
      balanceRemarks: [],
      currentRow: {}
    }
  },

  watch: {
  },

  mounted () {
    // this.getEnum()
    this.getBalanceProgramNames()
  },

  methods: {
    // // 数据字典
    // getEnum () {
    //   let groupName = 'balance.balancehandle'
    //   Common.getEnum(groupName, this.arrListDown)
    //   // console.log('数据字典：', this.arrListDown)
    // },

    /**
     * 分页查询接口
     * @param {Object} obj {pageIndex, pageSize}
     */
    async query () {
      var data = {
        Year: this.currentRow.periodYear,
        Month: this.currentRow.periodMonth,
        CompanyID: this.currentRow.companyID
      }
      let res = await ReceivableBillApi.getBalanceRemarksLog(data)
      console.log('差额处理弹窗列表res: ', res)
      if (res.status === 200 && res.data.success) {
        this.tableData = res.data.data
        console.log('🌈🌈🌈: ', this.tableData)
        localStorage.setItem('tempAddBalanceArr', JSON.stringify(res.data.data))
      } else {
        this.tableData = []
      }
      // this.loading = false
    },

    cancel () {
      this.isShowBalanceProcessModal = false
      Object.keys(this.formData).forEach(key => {
        this.formData[key] = ''
      })
      this.tableData = []
    },

    // 确定差额处理
    async handleSubmit () {
      var data = {
        Year: this.currentRow.periodYear,
        Month: this.currentRow.periodMonth,
        CompanyID: this.currentRow.companyID,
        CompanyName: this.currentRow.companyName,
        Balance: this.currentRow.currentBalanceTotal,
        BalanceRemarks: this.tableData
      }
      console.log('🐟', data)
      let res = await ReceivableBillApi.postReceivableBalanceLog(data)
      console.log('确定差额处理res: ', res)
      if (res.status === 200 && res.data.success) {
        this.$Message.success(res.data.message)
        this.isShowBalanceProcessModal = false
        this.$emit('query')
        setTimeout(() => {
          localStorage.removeItem('tempAddBalanceArr')
        }, 500)
      } else {
        this.$Message.error({
          content: res.data.message,
          duration: 10,
          closable: true
        })
      }
    },

    // 添加差额
    handleAddBalance () {
      var arr = []
      var that = this
      var tempAddBalanceArr = JSON.parse(localStorage.getItem('tempAddBalanceArr'))
      if (tempAddBalanceArr) {
        arr = tempAddBalanceArr
      }
      var that = this
      this.$refs.formData.validate((valid) => {
        if (valid) {
          arr.unshift(this.formData)
          localStorage.setItem('tempAddBalanceArr', JSON.stringify(arr))
          setTimeout(() => {
            that.tableData = JSON.parse(localStorage.getItem('tempAddBalanceArr'))
            Object.keys(that.formData).forEach(key => {
              that.formData[key] = ''
            })
          }, 100)
        }
      })
    },

    // 删除差额
    handleDel (index) {
      this.tableData.splice(index, 1)
      var tempAddBalanceArr = JSON.parse(localStorage.getItem('tempAddBalanceArr'))
      if (tempAddBalanceArr) {
        tempAddBalanceArr.splice(index, 1)
      }
      localStorage.setItem('tempAddBalanceArr', JSON.stringify(tempAddBalanceArr))
    },

    // 获取差额所属项目
    async getBalanceProgramNames () {
      let res = await ReceivableBillApi.getBalanceProgramNames()
      // console.log('获取差额所属项目res: ', res)
      if (res.status === 200 && res.data.success === true) {
        this.arrListDown.balanceProgramNames = res.data.data
      }
    },

    // 差额所属项目下拉改变
    balanceInsuranceNameChange (valueObj) {
      var tempArr = ['Salary', 'IncomeTax', 'HandlingFee', 'SF']
      if (valueObj) {
        this.formData.insuranceName = valueObj.label
        console.log('差额所属项目下拉改变valueObj: ', valueObj)
        this.arrListDown.balanceProgramNames.map(item => {
          if (item.code === valueObj.value) {
            console.log('item: ', item)
            this.getBalanceNos(item.group)
          }
        })

        if (tempArr.indexOf(valueObj.value) !== -1) {
          this.formItem.map(item => {
            if (item.prop === 'insureNo') {
              item.isShow = false
            }
            if (item.prop === 'insureNoOther') {
              item.isShow = true
            }
          })
        } else {
          this.formItem.map(item => {
            if (item.prop === 'insureNo') {
              item.isShow = true
            }
            if (item.prop === 'insureNoOther') {
              item.isShow = false
            }
          })
        }
      }
    },

    // 获取差额所属编号
    async getBalanceNos (group) {
      var params = {
        companyID: this.currentRow.companyID,
        group: group,
        year: this.currentRow.periodYear
      }
      let res = await ReceivableBillApi.getBalanceNos(params)
      console.log('.............................', res)
      if (res.status === 200 && res.data.success === true && res.data.data[0] != null) {
        this.arrListDown.balanceNos = res.data.data
      } else {
        this.arrListDown.balanceNos = []
        this.formData.insureNo = ''
      }
    }
  }
}
</script>

<style lang="less" scope>
</style>
